package com.wyix.controller;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @author wangdx
 * @since 2025/8/5
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置请求/响应编码（防中文乱码）
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remember = request.getParameter("remember");

        // 模拟验证（实际项目应查数据库）
        if ("admin".equals(username) && "123".equals(password)) {
            // 创建Session存储用户状态
            HttpSession session = request.getSession();
            session.setAttribute("user", username);
            session.setMaxInactiveInterval(3600); // 会话有效期1小时

            // "记住我"功能：用Cookie存储用户名
            if ("on".equals(remember)) {
                Cookie cookie = new Cookie("username", username);
                cookie.setMaxAge(7 * 24 * 3600); // 有效期7天
                cookie.setPath(request.getContextPath()); // 限制Cookie作用范围
                response.addCookie(cookie);
            }

            // 重定向到首页
            response.sendRedirect(request.getContextPath() + "/home.jsp");
        } else {
            response.getWriter().write("用户名或密码错误");
        }
    }
}